<template>
  <el-drawer
    v-model="drawerVisible"
    class="add-task-drawer"
    :size="props.size"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <template #header>
      <div class="text-lg font-semibold">{{ props.title }}</div>
    </template>
    <!-- 内容 -->
    <div class="user-info-content">
      <!-- 头像区域 -->
      <div class="avatar-section flex items-center justify-center">
        <div class="avatar-container">
          <el-avatar :size="80" :src="avatarPreview || formData.avatar" />
          <div class="edit-icon">
            <el-upload
              :show-file-list="false"
              :before-upload="beforeAvatarSelect"
              :http-request="handleAvatarUpload"
              accept="image/*"
            >
              <el-icon><Edit /></el-icon>
            </el-upload>
          </div>
        </div>
      </div>

      <el-form
        ref="formRef"
        :model="formData"
        label-width="100px"
        class="user-form"
      >
        <!-- 基本信息 -->
        <el-form-item label="姓名">
          <el-input v-model="formData.doctorName" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="formData.gender">
            <el-radio value="1">男</el-radio>
            <el-radio value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="手机号">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="角色">
          <el-input v-model="formData.role" placeholder="请输入角色，如 医生" />
        </el-form-item>

        <el-form-item label="医龄">
          <el-input v-model="formData.practiceYears" placeholder="请输入医龄" />
        </el-form-item>

        <el-form-item label="擅长科目">
          <el-input
            v-model="formData.projects"
            type="textarea"
            :rows="3"
            placeholder="请输入擅长科目，如 内科、外科"
          />
        </el-form-item>

        <!-- 个人标签 -->
        <el-form-item label="个人标签">
          <div class="tags-container">
            <div class="sub-tags-container">
              <div
                v-for="(tag, index) in formData.tags"
                :key="index"
                class="health-tag selected"
                @click="removeTag(index)"
              >
                {{ tag }}
                <span class="close-icon">×</span>
              </div>
              <div
                v-if="!tagInputVisible"
                class="health-tag add-tag"
                @click="showTagInput"
              >
                <span class="add-icon">+</span>
                添加标签
              </div>
            </div>
            <el-input
              v-if="tagInputVisible"
              ref="tagInputRef"
              v-model="tagInputValue"
              size="small"
              class="tag-input"
              placeholder="输入后回车"
              @keyup.enter="confirmTag"
              @blur="confirmTag"
            />
          </div>
        </el-form-item>

        <!-- 个人形象照 -->
        <el-form-item label="个人形象照">
          <div class="appearance-photo">
            <div class="photo-container">
              <img
                v-if="appearancePreview || formData.appearance"
                :src="appearancePreview || formData.appearance"
                alt="个人形象照"
                class="photo-image"
              />
              <div v-else class="photo-placeholder">
                <el-icon><Picture /></el-icon>
                <span>请选择图片</span>
              </div>
              <div class="photo-edit">
                <el-upload
                  :show-file-list="false"
                  :before-upload="beforeAppearanceSelect"
                  :http-request="handleAppearanceUpload"
                  accept="image/*"
                >
                  <el-button circle size="small">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                </el-upload>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button
          type="primary"
          style="margin-left: 10px"
          @click="handleSubmit"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
import { type FormInstance } from "element-plus";
import { defineEmits, defineExpose, defineProps, nextTick, ref } from "vue";
import { Edit, CreditCard, Picture } from "@element-plus/icons-vue";
import { reportApi } from "@/api/report-api";
import { knowledgeApi } from "@/api/knowledge";
import {
  getDoctorInfo,
  updateDoctorInfo,
  type DoctorInfoVO,
  type DoctorUpdateFrom
} from "@/api/user";
// 定义属性
const props = defineProps({
  title: {
    type: String,
    default: "个人信息"
  },
  size: {
    type: String,
    default: "500px"
  }
});

// 定义事件
const emit = defineEmits(["save", "close"]);
// 抽屉显示状态
const drawerVisible = ref(false);
const loading = ref(false);
const appearancePreview = ref<string>("");

// 表单引用
const formRef = ref<FormInstance>();
// 表单数据
const formData = ref<DoctorInfoVO>({
  doctorUserId: undefined,
  doctorName: "",
  phone: "",
  role: "",
  projects: "",
  profile: "",
  tags: [],
  avatar: "",
  appearance: "",
  gender: "",
  practiceYears: 0
});

// 标签输入
const tagInputVisible = ref(false);
const tagInputValue = ref("");
const tagInputRef = ref();
const showTagInput = () => {
  tagInputVisible.value = true;
  nextTick(() => tagInputRef.value?.focus());
};
const confirmTag = () => {
  const value = tagInputValue.value.trim();
  if (value) {
    if (!formData.value.tags) formData.value.tags = [];
    (formData.value.tags as string[]).push(value);
  }
  tagInputVisible.value = false;
  tagInputValue.value = "";
};
const removeTag = (index: number) => {
  (formData.value.tags as string[])?.splice(index, 1);
};

const beforeAppearanceSelect = (rawFile: File) => {
  const isImage = rawFile.type.startsWith("image/");
  const isLt5M = rawFile.size / 1024 / 1024 < 5;
  if (!isImage) {
    ElMessage.error("仅支持图片文件");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小需小于5MB");
    return false;
  }
  return true;
};

// 自定义上传实现：获取预签名URL -> PUT 上传 -> 设置 objectKey
const handleAppearanceUpload = async (options: any) => {
  try {
    const file: File = options.file;
    console.log("[UserInfo] 开始上传形象照:", file.name, file.type, file.size);
    const presigned = await reportApi.presignedApi({
      fileName: file.name,
      fileType: 1 // 图片类别
    });
    const url = presigned?.data?.presignedUrl as string;
    const objectKey = presigned?.data?.objectKey as string;
    const accessUrl = presigned?.data?.fileAccessUrl as string;
    if (!url || !objectKey) throw new Error("获取预签名URL失败");

    const resp = await fetch(url, {
      method: "PUT",
      body: file,
      headers: { "Content-Type": file?.type || "application/octet-stream" }
    });
    if (!resp.ok) throw new Error(`上传失败: ${resp.status}`);

    formData.value.appearance = accessUrl;
    formData.value.appearanceKey = objectKey;

    appearancePreview.value = accessUrl || appearancePreview.value;
    ElMessage.success("形象照上传成功");
    console.log("[UserInfo] 形象照上传成功, objectKey:", objectKey);
    options.onSuccess && options.onSuccess({}, file);
  } catch (error: any) {
    console.error("[UserInfo] 形象照上传失败:", error);
    ElMessage.error(error?.message || "形象照上传失败");
    options.onError && options.onError(error);
  }
};
// 头像上传相关
const avatarPreview = ref<string>("");

const beforeAvatarSelect = (rawFile: File) => {
  const isImage = rawFile.type.startsWith("image/");
  const isLt5M = rawFile.size / 1024 / 1024 < 5;
  if (!isImage) {
    ElMessage.error("仅支持图片文件");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小需小于5MB");
    return false;
  }
  return true;
};

// 头像上传实现：获取预签名URL -> PUT 上传 -> 设置 objectKey
const handleAvatarUpload = async (options: any) => {
  try {
    const file: File = options.file;
    console.log("[UserInfo] 开始上传头像:", file.name, file.type, file.size);
    const presigned = await reportApi.presignedApi({
      fileName: file.name,
      fileType: 1 // 图片类别
    });
    const url = presigned?.data?.presignedUrl as string;
    const objectKey = presigned?.data?.objectKey as string;
    const accessUrl = presigned?.data?.fileAccessUrl as string;
    if (!url || !objectKey) throw new Error("获取预签名URL失败");

    const resp = await fetch(url, {
      method: "PUT",
      body: file,
      headers: { "Content-Type": file?.type || "application/octet-stream" }
    });
    if (!resp.ok) throw new Error(`上传失败: ${resp.status}`);

    formData.value.avatar = accessUrl;
    formData.value.avatarKey = objectKey;

    avatarPreview.value = accessUrl || avatarPreview.value;
    ElMessage.success("头像上传成功");
    console.log("[UserInfo] 头像上传成功, objectKey:", objectKey);
    options.onSuccess && options.onSuccess({}, file);
  } catch (error: any) {
    console.error("[UserInfo] 头像上传失败:", error);
    ElMessage.error(error?.message || "头像上传失败");
    options.onError && options.onError(error);
  }
};

// 提交保存
const handleSubmit = async () => {
  try {
    if (!formData.value.doctorUserId) {
      ElMessage.error("缺少医生用户ID，无法保存");
      return;
    }
    loading.value = true;
    const payload: DoctorUpdateFrom = {
      doctorUserId: formData.value.doctorUserId!,
      role: formData.value.role || "",
      projects: formData.value.projects || "",
      profile: formData.value.profile || "",
      tags: formData.value.tags || [],
      // appearance: formData.value.appearance || "",
      // avatar: formData.value.avatar || "",
      gender: formData.value.gender,
      practiceYears: formData.value.practiceYears,
      actualName: formData.value.doctorName || "",
      appearanceKey: formData.value.appearanceKey || "",
      avatarKey: formData.value.avatarKey || "",
      phone: formData.value.phone || ""
    } as any;
    console.log("[UserInfo] 提交保存 DoctorUpdateFrom:", payload);
    const res = await updateDoctorInfo(payload);
    if ((res as any)?.code === 0) {
      ElMessage.success((res as any)?.message || "保存成功");
      drawerVisible.value = false;
      emit("save");
    } else {
      ElMessage.error((res as any)?.message || "保存失败");
    }
  } catch (error) {
    console.error("[UserInfo] 保存失败:", error);
    ElMessage.error("保存失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 对外暴露的方法
defineExpose({
  // 打开抽屉的方法
  open(report) {
    console.log("[UserInfo] 打开抽屉, 参数:", report);
    // 打开时加载医生信息
    fetchDoctorInfo();
    drawerVisible.value = true;
  },
  // 关闭抽屉的方法
  close() {
    drawerVisible.value = false;
  }
});

// 获取医生信息
const fetchDoctorInfo = async () => {
  try {
    loading.value = true;
    console.log("[UserInfo] 开始获取医生信息");
    const res = await getDoctorInfo();
    const data = res.data as DoctorInfoVO;
    formData.value = {
      ...formData.value,
      ...data,
      tags: data.tags || []
    } as any;
    console.log("[UserInfo] 医生信息加载完成:", data);
  } catch (error) {
    console.error("[UserInfo] 获取医生信息异常:", error);
    ElMessage.error("获取医生信息失败");
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss">
/* 移除 scoped，使用全局样式 */
.add-task-drawer {
  .follow-plan {
    padding: 20px;
  }
  .el-drawer__header {
    padding: 20px 24px !important;
    border-bottom: 1px solid #f0f0f0 !important;
    margin-bottom: 0 !important;
    background-color: #fff !important;
  }

  .el-drawer__title {
    font-size: 16px !important;
    font-weight: 600 !important;
    color: #333 !important;
  }

  .el-drawer__body {
    padding: 0 !important;
    background-color: #fafafa !important;
  }

  .el-form-item__label {
    font-weight: 500 !important;
    color: #333 !important;
    font-size: 14px !important;
  }

  .el-input__wrapper {
    border-radius: 6px !important;
    transition: all 0.3s ease !important;
  }

  .el-textarea .el-textarea__inner {
    border-radius: 6px !important;
    transition: all 0.3s ease !important;
  }

  .el-date-editor,
  .el-time-picker {
    width: 100% !important;
  }

  .el-button--primary {
    border-radius: 6px !important;
    font-weight: 500 !important;
    padding: 12px 32px !important;
    font-size: 14px !important;
    background-color: #409eff !important;
    border-color: #409eff !important;
    color: #fff !important;

    &:hover {
      background-color: #66b1ff !important;
      border-color: #66b1ff !important;
    }
  }
}

/* 组件内部样式 */
.add-task-drawer .p-6 {
  padding: 24px !important;
  background-color: #fff !important;
  margin: 0 !important;
  min-height: calc(100vh - 60px) !important;
}

.add-task-drawer .el-form {
  max-width: 100% !important;
}

.add-task-drawer .el-form-item {
  margin-bottom: 24px !important;
}

.add-task-drawer .el-form-item:last-child {
  margin-bottom: 0 !important;
}

/* 用户信息内容区域 */
.user-info-content {
  padding: 24px;
  background: #fff;
}

/* 头像区域 */
.avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 32px;

  .avatar-container {
    position: relative;

    .edit-icon {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 24px;
      height: 24px;
      background: #fff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      cursor: pointer;

      .el-icon {
        font-size: 12px;
        color: #666;
      }
    }
  }

  .id-recognition {
    .el-button {
      width: 40px;
      height: 40px;
      background: #f5f7fa;
      border: 1px solid #e4e7ed;

      .el-icon {
        color: #909399;
      }
    }
  }
}

/* 表单样式 */
.user-form {
  .el-form-item {
    margin-bottom: 20px;

    .el-form-item__label {
      color: #606266;
      font-weight: 500;
    }

    .el-input__wrapper {
      border-radius: 4px;
    }

    .el-textarea__inner {
      border-radius: 4px;
    }
  }
}

/* 个人形象照 */
.appearance-photo {
  .photo-container {
    position: relative;
    width: 150px;
    height: 200px;
    border-radius: 8px;
    overflow: hidden;
    background: #f5f7fa;
    border: 1px solid #e4e7ed;

    .photo-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
    }

    .photo-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #c0c4cc;
      font-size: 14px;

      .el-icon {
        font-size: 32px;
        margin-bottom: 8px;
      }
    }

    .photo-edit {
      position: absolute;
      bottom: 8px;
      right: 8px;

      .el-button {
        background: rgba(255, 255, 255, 0.9);
        border: none;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

        .el-icon {
          color: #666;
        }
      }
    }
  }
}
</style>

<style lang="scss" scoped>
/* 标签容器 - 使用 healthLabel 的样式 */
.tags-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sub-tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 6px 0;
  align-items: center;
}

.health-tag {
  height: 24px;
  padding: 0 12px;
  text-align: center;
  line-height: 24px;
  border-radius: 17px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #d9d9d9;
  background-color: #f5f5f5;
  color: #666;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;

  &:hover {
    border-color: #1890ff;
  }

  &.selected {
    border-color: #1890ff;
    color: #1890ff;
    background-color: transparent;
    padding-right: 24px; /* 为关闭按钮留出空间 */

    .close-icon {
      position: absolute;
      right: 6px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 14px;
      font-weight: bold;
      cursor: pointer;
      opacity: 0.7;
      transition: opacity 0.2s ease;

      &:hover {
        opacity: 1;
      }
    }
  }

  &.add-tag {
    border-style: solid;
    border-color: #2dafff;
    background-color: transparent;
    color: #2dafff;

    &:hover {
      background-color: #f0f9ff;
    }

    .add-icon {
      font-size: 16px;
      font-weight: bold;
      margin-top: -3px;
    }
  }
}

.tag-input {
  width: 120px;
  height: 24px;
  margin-left: 8px;
}
</style>
